// 路由预加载工具 - 优化版本
export const preloadRoute = (routeName: string) => {
  // 预加载常用路由 - 减少一次性加载数量
  const routeMap: Record<string, () => Promise<any>> = {
    'Dashboard': () => import('@/views/Dashboard.vue'),
    'TableList': () => import('@/views/monitor/TableList.vue'),
    'FlinkJobs': () => import('@/views/flink/FlinkJobs.vue')
  }

  const loader = routeMap[routeName]
  if (loader) {
    // 使用 requestIdleCallback 在空闲时间预加载
    if ('requestIdleCallback' in window) {
      requestIdleCallback(() => loader(), { timeout: 2000 })
    } else {
      // 降级处理
      setTimeout(() => loader(), 200)
    }
  }
}

// 预加载核心路由 - 减少初始加载
export const preloadCoreRoutes = () => {
  const coreRoutes = ['Dashboard']
  
  // 分批预加载，避免阻塞
  coreRoutes.forEach((route, index) => {
    setTimeout(() => preloadRoute(route), index * 100)
  })
}

// 预加载所有常用路由 - 延迟执行
export const preloadAllRoutes = () => {
  const routes = [
    'TableList', 
    'FlinkJobs',
    'TaskMonitor',
    'AlertRules',
    'ReportList',
    'SystemConfigs'
  ]

  // 使用 requestIdleCallback 分批预加载
  if ('requestIdleCallback' in window) {
    routes.forEach((route, index) => {
      requestIdleCallback(() => preloadRoute(route), { timeout: 3000 + index * 500 })
    })
  } else {
    // 降级处理 - 延迟分批加载
    routes.forEach((route, index) => {
      setTimeout(() => preloadRoute(route), 1000 + index * 200)
    })
  }
}

// 智能预加载 - 根据用户行为预测，减少不必要的预加载
export const smartPreload = (currentRoute: string) => {
  // 减少预加载的路由数量
  const preloadMap: Record<string, string[]> = {
    'Dashboard': ['TableList'],
    'TableList': ['TableDetail'],
    'FlinkJobs': ['FlinkMappings'],
    'TaskMonitor': ['FlinkJobs'],
    'AlertRules': ['AlertHistory'],
    'ReportList': ['ReportTemplates']
  }

  const routesToPreload = preloadMap[currentRoute] || []
  
  // 限制同时预加载的路由数量
  if (routesToPreload.length > 0) {
    const routeToPreload = routesToPreload[0] // 只预加载一个
    requestIdleCallback(() => preloadRoute(routeToPreload), { timeout: 2000 })
  }
} 